package com.example.lenovo.asia5b.my.order.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.example.lenovo.asia5b.commodity.activity.CommodityDetActivity;
import com.example.lenovo.asia5b.home.bean.UserBean;
import com.example.lenovo.asia5b.my.order.adapter.OrderParticularsAdapter;
import com.example.lenovo.asia5b.my.order.bean.OrderDetailBean;
import com.example.lenovo.asia5b.ui.LoadingDalog;
import com.example.lenovo.asia5b.ui.photoview.ImagePagerActivity;
import com.example.lenovo.asia5b.util.DateUtils;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.MD5;
import com.example.lenovo.asia5b.util.Setting;
import com.example.lenovo.asia5b.util.SharedPreferencesUtils;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import app.BaseActivity;
import fay.frame.ui.U;

import static com.wushi.lenovo.asia5b.R.id.public_btn_left;

/**
 * Created by lenovo on 2017/6/21.
 */

public class InvoiceDetailsActivity extends BaseActivity implements ICallBack {

    private LayoutInflater inflater;
    private View header;
    private View botton;
    private ListView  fragmentListView;
    private OrderParticularsAdapter orderParticularsAdapter;
    private String order_id;
    private LoadingDalog loadingDalog;
    //头部TextView
    private TextView activity_order_details_botton,activity_order_details_mobile,activity_order_details_transport,activity_order_details_shipping_name,
            activity_order_details_city,activity_order_details_address,activity_order_details_statu;
    //尾部TextView
    private TextView activity_order_details_pack_fee,//activity_order_details_goods_count,
            activity_order_details_insure_fee,activity_order_details_shipping_fee,
            activity_order_details_pay_fee,activity_order_details_tax,activity_order_details_bonus,activity_order_details_integral_money,
            //activity_order_details_order_count,
            activity_order_details_money_paid,activity_order_details_pay_points,activity_order_details_order_sn,
            activity_order_details_pay_sn,activity_order_details_add_time,activity_order_details_order_pay_time,activity_order_details_order_send_time,
            activity_order_details_order_sign_time,txt_dcj_jg;
    private LinearLayout ll_bcj,activity_order_details_ll_points;
    private LinearLayout ll_send_time;
    private ArrayList<String> list_imag = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_invoice_details);
        inflater = LayoutInflater.from(this);
        initView();
    }

    public void initView() {
        loadingDalog = new LoadingDalog(InvoiceDetailsActivity.this);
        loadingDalog.show();
        F.id(R.id.btn_change_information).clicked(this);
        F.id(R.id.public_title_name).text(getResources().getString(R.string.invoice_details));
        F.id(public_btn_left).clicked(this);
        F.id(R.id.public_txt_righe).clicked(this);
        orderParticularsAdapter = new OrderParticularsAdapter(this);
        fragmentListView = findViewById(R.id.activity_orders_particulars);
        fragmentListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                if (i >= 0 && i < orderParticularsAdapter.getCount()) {
//                    Intent intent = new Intent(InvoiceDetailsActivity.this, CommodityDetActivity.class);
//                    intent.putExtra("goods_id",((OrderDetailBean)adapterView.getAdapter().getItem(i)).goods_id);
//                    startActivity(intent);
//                }
                try {
                    Intent intent = new Intent(InvoiceDetailsActivity.this, CommodityDetActivity.class);
                    intent.putExtra("goods_id",((OrderDetailBean)adapterView.getAdapter().getItem(i)).goods_id);
                    startActivity(intent);
                } catch (Exception e){

                }
            }
        });

        header = (View)inflater.inflate(R.layout.activity_order_details_header,null);
        activity_order_details_botton = (TextView)header.findViewById(R.id.activity_order_details_consignee);//收获人
        activity_order_details_mobile = (TextView)header.findViewById(R.id.activity_order_details_mobile);//电话
        activity_order_details_transport = (TextView)header.findViewById(R.id.activity_order_details_transport);//国际运输方式
        activity_order_details_shipping_name = (TextView)header.findViewById(R.id.activity_order_details_shipping_name);//本地配送方式
        activity_order_details_city = (TextView)header.findViewById(R.id.activity_order_details_city);//邮编
        activity_order_details_address = (TextView)header.findViewById(R.id.activity_order_details_address);//收获地址
        activity_order_details_statu = (TextView)header.findViewById(R.id.activity_order_details_statu);//订单状态

        botton = (View)inflater.inflate(R.layout.activity_order_details_botton,null);
        activity_order_details_pack_fee = (TextView)botton.findViewById(R.id.activity_order_details_pack_fee);//保险费
        //activity_order_details_goods_count = (TextView)botton.findViewById(R.id.activity_order_details_goods_count);//商品总价
        activity_order_details_insure_fee = (TextView)botton.findViewById(R.id.activity_order_details_insure_fee);//国际运费
        activity_order_details_shipping_fee = (TextView)botton.findViewById(R.id.activity_order_details_shipping_fee);//中国运费
        activity_order_details_pay_fee = (TextView)botton.findViewById(R.id.activity_order_details_pay_fee);//本地派送费
        activity_order_details_tax = (TextView)botton.findViewById(R.id.activity_order_details_tax);//手续费
        activity_order_details_bonus = (TextView)botton.findViewById(R.id.activity_order_details_bonus);//代金券
        activity_order_details_integral_money = (TextView)botton.findViewById(R.id.activity_order_details_integral_money);//消费积分金额
        //activity_order_details_order_count = (TextView)botton.findViewById(R.id.activity_order_details_order_count);//订单总价
        activity_order_details_money_paid = (TextView)botton.findViewById(R.id.activity_order_details_money_paid);//已付款金额
        activity_order_details_pay_points = (TextView)botton.findViewById(R.id.activity_order_details_pay_points);//返还积分
        activity_order_details_order_sn = (TextView)botton.findViewById(R.id.activity_order_details_order_sn);//订单ID
        activity_order_details_pay_sn = (TextView)botton.findViewById(R.id.activity_order_details_pay_sn);//订单发票号
        activity_order_details_add_time = (TextView)botton.findViewById(R.id.activity_order_details_add_time);//提交时间
        activity_order_details_order_pay_time = (TextView)botton.findViewById(R.id.activity_order_details_order_pay_time);//支付时间
        activity_order_details_order_send_time = (TextView)botton.findViewById(R.id.activity_order_details_order_send_time);//发货时间
        activity_order_details_order_sign_time = (TextView)botton.findViewById(R.id.activity_order_details_order_sign_time);//签收时间
        ll_send_time = (LinearLayout)botton.findViewById(R.id.ll_send_time);
        ll_bcj = (LinearLayout)botton.findViewById(R.id.ll_bcj);//补差价
        txt_dcj_jg = (TextView)botton.findViewById(R.id.txt_dcj_jg);//补差价
        ll_bcj.setOnClickListener(this);
        activity_order_details_ll_points = (LinearLayout)botton.findViewById(R.id.activity_order_details_ll_points);//返还积分

        fragmentListView.addHeaderView(header);
        fragmentListView.addFooterView(botton);

        Intent intent = getIntent();
        order_id = intent.getStringExtra("order_id");
        getPostAPI();
//        U.Toast(this,order_id);
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case public_btn_left:
                finish();
                break;
            case R.id.ll_bcj:
                intent = new Intent(InvoiceDetailsActivity.this, MakeMoneyTwoActivity.class);
                intent.putExtra("order_id",order_id);
                startActivity(intent);
                break;
            case  R.id.public_txt_righe:
                imageBrower(0);
                break;
            default:
                break;
        }
    }

    private void getPostAPI(){
        try{
            UserBean userBean = (UserBean) SharedPreferencesUtils.getObjectFromShare("user");
            if(userBean != null){
                Date date = new Date();
                String invoiceDetailURL = Setting.ORDERDETAILS;
                String user_id = userBean.user_id;
                String time = String.valueOf(date.getTime());

                Map<String,String> map = new HashMap<String,String>();
                map.put("user_id",user_id);
                map.put("order_id",order_id);
                map.put("time",time);

                String[] sortStr = {"user_id"+user_id,"order_id"+order_id,"time"+time};
                String sort = Logic.sortToString(sortStr);
                String md5 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sort));
                map.put("sign",md5);

                JsonTools.getJsonAll(this,invoiceDetailURL,map,0);
            }

        }catch (Exception e){
            Log.e("订单详情error",e.getMessage());
        }
    }

    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result= null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;
            try{
                if(result != null){
                    if(action == 0){
                        JSONObject jsonObect = (JSONObject)result;
                        int state = jsonObect.getInt("State");
                        if(state == 0){
                            JSONObject order = jsonObect.getJSONObject("order");
                            String order_status = order.getString("order_status");
                        /*begin 头部信息 **/
                            activity_order_details_botton.setText("："+order.getString("consignee"));//收货人
                            activity_order_details_mobile.setText(order.getString("mobile"));//电话
                            activity_order_details_transport.setText("："+order.getString("transport"));//国际运输方式
                            activity_order_details_shipping_name.setText("："+order.getString("shipping_name"));//本地配送方式
                            activity_order_details_city.setText("："+order.getString("city"));//邮编
                            StringBuffer sbAddress = new StringBuffer();
                            sbAddress.append(order.getString("country"));//国家
                            sbAddress.append(" "+order.getString("province"));//州
                            sbAddress.append(" "+order.getString("address"));//详细地址
                            activity_order_details_address.setText(sbAddress.toString());//收货地址
//                        activity_order_details_statu.setText(order.getString("orderStatu"));//订单状态
                        /*end 头部信息 **/

                        /*begin 尾部信息**/
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

                            activity_order_details_pack_fee.setText("RM "+order.getString("pack_fee"));//保险费
                            //activity_order_details_goods_count.setText(order.getString("goods_count"));//商品总价
                            activity_order_details_insure_fee.setText("RM "+order.getString("insure_fee"));//国际运费
                            activity_order_details_shipping_fee.setText("RM "+order.getString("shipping_fee"));//中国运费
                            activity_order_details_pay_fee.setText("RM "+order.getString("pay_fee"));//本地派送费
                            activity_order_details_tax.setText("RM "+order.getString("tax"));//手续费
                            activity_order_details_bonus.setText("RM "+order.getString("bonus"));//代金券
                            activity_order_details_integral_money.setText(order.getString("integral_money"));//消费积分金额
                            //activity_order_details_order_count.setText(order.getString("order_count"));//订单总价
                            activity_order_details_money_paid.setText("RM "+order.getString("money_paid"));//已付款金额
                            //判断订单是否已经完成，如果完成就显示积分，
                            //如果订单状态不是完成，就不显示积分
                            if(Integer.parseInt(order_status) == 10){
                                activity_order_details_pay_points.setText(order.getString("pay_points"));//返还积分
                            }else{
                                activity_order_details_ll_points.setVisibility(View.GONE);
                            }
                            activity_order_details_order_sn.setText(order.getString("order_sn"));//订单ID
                            activity_order_details_pay_sn.setText(order.getString("pay_sn"));//订单发票号

                            String differ_price = order.getString("differ_price");
                            if (TextUtils.isEmpty(differ_price)) {
                                ll_bcj.setVisibility(View.GONE);
                            } else {
                                double aa = Double.parseDouble(differ_price);
                                if (aa <= 0 ){
                                    ll_bcj.setVisibility(View.GONE);
                                } else {
                                    txt_dcj_jg.setText("RM "+order.getString("differ_price"));//补差价
                                }
                            }
                            //提交时间
                            String add_timeStr = order.getString("add_time");
                            String add_time = DateUtils.timedate(add_timeStr);
                            activity_order_details_add_time.setText(add_time);
                            //支付时间
                            String order_pay_timeStr = order.getString("order_pay_time");
                            String order_pay_time = null;
                            if(TextUtils.equals("0",order_pay_timeStr)){
                                order_pay_time = "--:--:--";
                            }else{
                                order_pay_time = DateUtils.timedate(order_pay_timeStr);
                            }
                            activity_order_details_order_pay_time.setText(order_pay_time);
                            //发货时间
                            String order_send_timeStr = order.getString("order_send_time");
                            String order_send_time = null;
                            if(TextUtils.equals("0",order_send_timeStr)){
                                order_send_time = "--:--:--";
                            }else{
                                order_send_time = DateUtils.timedate(order_send_timeStr);
                                ll_send_time.setVisibility(View.VISIBLE);
                            }
                            activity_order_details_order_send_time.setText(order_send_time);
                            //签收时间
                            String order_sign_timeStr = order.getString("order_sign_time");
                            String order_sign_time = null;
                            if(TextUtils.equals("0",order_sign_timeStr)){
                                order_sign_time = "--:--:--";
                            }else{
                                order_sign_time = DateUtils.timedate(order_sign_timeStr);
                            }
                            activity_order_details_order_sign_time.setText(order_sign_time);
                        /*end 尾部信息**/

                        /*begin 包裹列表**/
                            JSONArray jsonArray = order.getJSONArray("goods_list");
                            List<OrderDetailBean> OrderDetailList = Logic.getListToBean(jsonArray,new OrderDetailBean());
                            orderParticularsAdapter.setOrderStatus(order_status);
                            orderParticularsAdapter.setOrderDetailBean(OrderDetailList);
                            fragmentListView.setAdapter(orderParticularsAdapter);
                            billListData();
                        /*end 包裹列表**/

                        }else if (state == 1) {
                            U.Toast(InvoiceDetailsActivity.this, getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(InvoiceDetailsActivity.this, getResources().getString(R.string.cscw));
                        } else if (state == 3) {
                            U.Toast(InvoiceDetailsActivity.this, getResources().getString(R.string.wdl));
                        }
                    } else if (action == 1) {
                        JSONObject jsonObject = (JSONObject) result;
                        int state = jsonObject.getInt("State");
                        if (state == 0) {
                            JSONArray jsonArray = jsonObject.getJSONArray("order_bills");
                            if (jsonArray.length()>0) {
                                F.id(R.id.public_txt_righe).visibility(View.VISIBLE);
                                F.id(R.id.public_txt_righe).text(getResources().getString(R.string.ckpj));
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                                    list_imag.add(jsonObject1.getString("image"));
                                }
                                list_imag.add(jsonObject.getString("order_total"));
                            }
                        }else if (state == 1) {
                            U.Toast(InvoiceDetailsActivity.this, getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(InvoiceDetailsActivity.this, getResources().getString(R.string.cscw));
                        }
                        loadingDalog.dismiss();
                    }
                }
            }catch (Exception e){
                Log.e("JSONError",e.getMessage());
            }
            loadingDalog.dismiss();
        }
    };

    @Override
    public void logicFinish(Object result, int action) {
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);
    }

    /**
     * 调用接口
     */
    public void billListData() {
        try {
            loadingDalog.show();
            Date date = new Date();
            UserBean userBean = (UserBean) SharedPreferencesUtils.getObjectFromShare("user");
            if (userBean != null) {
                String url = Setting.ORDER_NOTE;
                Map<String, String> map = new HashMap<String, String>();
                map.put("user_id", userBean.user_id);
                map.put("order_sn",activity_order_details_order_sn.getText().toString().trim());
                map.put("time", String.valueOf(date.getTime()));
                //排序
                String[] sortStr = {"user_id" + userBean.user_id,  "time" + date.getTime()};
                String sort = Logic.sortToString(sortStr);
                String md5 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sort));
                map.put("sign", md5);
                JsonTools.getJsonAll(this, url, map, 1);
            }
        } catch (Exception e) {
        }
    }

    /**
     * 打开图片查看器
     *
     * @param position
     */
    protected void imageBrower(int position) {
        Intent intent = new Intent(InvoiceDetailsActivity.this, ImagePagerActivity.class);
        // 图片url,为了演示这里使用常量，一般从数据库中或网络中获取
        intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, list_imag);
        intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
        startActivity(intent);
    }
}
